/*
 * @Author: amandayuan
 * @Date: 2024-06-19 09:16:14
 * @LastEditors: amandayuan
 * @Description: 财务模块-数字处理
 */
import numeral from "numeral";
import { isNullOrUnDef } from "./is";

/** 价格大写，需要考虑负数 */
function numberToChinese(num) {
  const units = [
    "",
    "拾",
    "佰",
    "仟",
    "万",
    "拾万",
    "佰万",
    "仟万",
    "亿",
    "拾亿",
    "佰亿",
    "仟亿",
  ];
  const chars = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const fractionUnits = ["角", "分"];
  /** 需要考虑负数 */
  const isLessZero = Number(num) < 0;
  /** 取绝对值 */
  const absNum = Math.abs(Number(num));
  /** 将数字转换为字符串，并分割成整数部分和小数部分 */
  const [integerPart, fractionPart] = absNum?.toString()?.split?.(".") ?? [];

  /** 处理整数部分 */
  let integerResult = "";
  for (let i = 0; i < integerPart.length; i++) {
    const digit = parseInt(integerPart[i]);
    const unit = units[integerPart.length - 1 - i];
    integerResult += chars[digit] + unit;
  }

  /** 去掉整数部分末尾的 "零" */
  integerResult = integerResult
    .replace(/零(拾|佰|仟|万|亿)/g, "零")
    .replace(/零+/g, "零")
    .replace(/零$/, "")
    .replace(/零万/g, "万")
    .replace(/亿万/g, "亿")
    .replace(/壹拾/g, "拾");

  /** 处理小数部分 */
  let fractionResult = "";
  if (fractionPart) {
    for (let i = 0; i < fractionPart.length; i++) {
      const digit = parseInt(fractionPart[i]);
      const fractionUnit = fractionUnits[i];
      fractionResult += chars[digit] + fractionUnit;
    }
  }
  const result =
    fractionResult === ""
      ? (integerResult || "零") + "元整"
      : integerResult === ""
      ? fractionResult
      : integerResult + "元" + fractionResult;
  return isLessZero ? `负${result}` : result;
}

export { numberToChinese };

export const NumberUtils = {
  /**
   * 格式化输出number的值(format默认值是'0,0.00')，比如：format="0,0.00" num="10,000.00"
   * @param num 要格式化的数字
   * @param format 格式化格式
   * @param defaultValue 如果num为null或undefined，则默认返回defaultValue
   * @returns
   */
  format(num, format = "0,0.00", defaultValue = "") {
    if (isNullOrUnDef(num)) {
      return defaultValue;
    }
    if (isBlankString(num)) {
      return defaultValue;
    }
    return numeral(num).format(format);
  },
  /**
   * 对数字进行保留小数操作（默认保留两位小数）
   * @param num
   * @param fractionDigits
   * @returns
   */
  toFixed(num, fractionDigits = 2) {
    const formatNum = Number(num) || 0;
    return formatNum.toFixed(fractionDigits);
  },
};

/** 判断值为null 或 undefined */
export function isNotNullOrUndefined(item) {
  return item !== null && item !== undefined;
}
/** 判断为空字符串 */
export function isBlankString(item) {
  return item === "";
}

export function int(a) {
  return parseInt(a, 10);
}
